<template>
  <div class="sjht-upload">
    <a-spin :delay="100" :spinning="loading">
      <a-upload accept="image/*" :action="uploadUrl" :disabled="loading" withCredentials :beforeUpload="beforeUpload" listType="picture-card" :fileList="fileList" @change="onChange" @preview="onPreview">
        <template v-if="maxs==0 || fileList.length<maxs">
          <a-icon :type="loading?'loading':'plus'" style="font-size:32px" />
          <p>添加图片</p>
        </template>
      </a-upload>
    </a-spin>
    <!-- 预览图片 -->
    <a-modal :visible="previewVisible" :footer="null" @cancel="()=>previewVisible=false">
      <img style="width:100%" :src="previewImage" />
    </a-modal>
  </div>
</template>
<script>
let getlist = function (list) {
  if ((list ?? []).length > 0) {
    return list.map(m => {
      return {
        uid: Math.random().toString(36).substr(2),
        name: Math.random().toString(36).substr(2),
        url: m,
        status: 'done'
      }
    })
  } else return []
}
import { Upload } from 'ant-design-vue'
export default {
  name: 'SjhtUpload',
  components: {
    [Upload.name]: Upload
  },
  model: {
    prop: 'list',
    event: 'change'
  },
  props: {
    maxs: {
      type: Number,
      default: 0
    }, //最多上传图片数,0为不限制
    list: Array //['url','url']已经上传的文件列表
  },
  data() {
    return {
      uploadUrl: process.env.VUE_APP_UPLOAD_URL, //上传地址
      loading: false,
      fileList: getlist(this.list),
      previewVisible: false,
      previewImage: null
    }
  },
  methods: {
    // 开始上传前进行验证
    beforeUpload(file) {
      if (this.loading) return false
      const isFormats = ['image/jpg', 'image/jpeg', 'image/png', 'image/gif', 'image/bmp'].includes(file.type)
      if (!isFormats) {
        this.$message.error('只能上传JPG,PNG,GIF,BMP格式的图片')
      }
      const isLt3M = file.size / 1024 / 1024 < 10
      if (!isLt3M) {
        this.$message.error('只能上传下于10MB的图片')
      }
      return isFormats && isLt3M
    },
    //上传文件改变时的函数
    onChange({ file, fileList }) {
      const { $message } = this
      const res = file.response
      switch (file.status) {
        case 'uploading': //上传中
          this.loading = true
          this.fileList = fileList
          break
        case 'done': //完成
          fileList.pop()
          if (res.code == 0) {
            fileList.push({
              uid: Math.random().toString(36).substr(2),
              name: file.name,
              url: res.data.netpath,
              status: 'done'
            })
            this.$emit('done', { ...res.data })
            this.$emit(
              'change',
              fileList.map(m => m.url)
            )
            $message.success('上传成功')
          } else {
            $message.error(res.message)
          }
          this.fileList = fileList
          this.loading = false
          break
        case 'error': //失败
          this.loading = true
          $message.error('上传失败')
          break
        case 'removed': //删除
          this.$confirm({
            title: '确定删除图片吗？',
            content: '删除图片后将不能找回，请谨慎操作。',
            okType: 'danger',
            onOk: () => {
              this.fileList = fileList
              this.$emit('removed', { id: file.uid })
              this.$emit(
                'change',
                fileList.map(m => m.url)
              )
              $message.success('删除成功')
              this.loading = false
              // this.loading = true
              // return req({ url: `/api/upload/del/${tag}/${file.uid}/` })
              //   .then(res => {
              //     $message.success(res)
              //   })
              //   .catch(err => {
              //     $message.error(err)
              //   })
              //   .finally(() => {
              //     this.loading = false
              //   })
            }
          })
          break
      }
      return
    },
    //预览图片
    async onPreview(file) {
      this.previewImage = file.url
      this.previewVisible = true
    }
  },
  watch: {
    list: function (n) {
      this.fileList = getlist(n)
    }
  }
}
</script>